package com.blockchain.front.servlets.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blockchain.framework.http.session.Session;
import com.blockchain.framework.http.session.authentication.AuthenticationException;
import com.blockchain.framework.http.session.authentication.VerifyCodeAuthentication;
import com.blockchain.framework.resource.PromptLevel;
import com.blockchain.framework.service.ServiceSession;
import com.blockchain.front.service.common.PasswordManage;
import com.blockchain.front.service.common.UserManage;
import com.blockchain.front.service.security.SecurityManage;

public class WjJymm extends AbstractSceurityServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void processGet(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		forwardView(request, response, getClass());
	}

	@Override
	protected void processPost(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		String password = request.getParameter("password");
		String repassword = request.getParameter("newPassword");
		String dxverifyCode = request.getParameter("dxverifyCode");

		UserManage usanage=serviceSession.getService(UserManage.class);
		String phone = usanage.getUser().iphone;
		if (!password.equals(repassword)) {
			getController().prompt(request, response, PromptLevel.ERROR, "两次输入不符");
			forward(request, response, getController().getViewURI(request, WjJymm.class));
			return;
		}
		
		  Session session = serviceSession.getSession();
		  VerifyCodeAuthentication authentication = new
		  VerifyCodeAuthentication();
		  authentication.setVerifyCode(dxverifyCode);
		  authentication.setVerifyCodeType("WJJYMM"+phone);
		  session.authenticateVerifyCode(authentication);
		 
		PasswordManage passwordManage = serviceSession.getService(PasswordManage.class);
		SecurityManage manage = serviceSession.getService(SecurityManage.class);
		int id = passwordManage.phoneExist(phone);
		try {
			if (id > 0) {
				manage.updateJymm(password, id);
				sendRedirect(request,response,getController().getViewURI(request,  WjJymm.class) + "?message=修改成功");
			}
		} catch (Exception e) {
			getController().prompt(request, response, PromptLevel.ERROR, e.getMessage());
			forward(request, response, getController().getViewURI(request, WjJymm.class));
		}

	}

	@Override
	protected void onThrowable(HttpServletRequest request, HttpServletResponse response, Throwable throwable)
			throws ServletException, IOException {
		if (throwable instanceof AuthenticationException) {
			getResourceProvider().log(throwable.getMessage());
			getController().prompt(request, response, PromptLevel.ERROR, "验证码已过期或验证码错误");
			forward(request, response, getController().getViewURI(request, WjJymm.class));
		}
	}
}